package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.controller.param.CreatePrizeParam;
import com.example.lotterysystem.controller.param.PageParam;
import com.example.lotterysystem.dao.dataobject.PrizeDO;
import com.example.lotterysystem.dao.mapper.PrizeMapper;
import com.example.lotterysystem.service.PictureService;
import com.example.lotterysystem.service.PrizeService;
import com.example.lotterysystem.service.dto.PageListDTO;
import com.example.lotterysystem.service.dto.PrizeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


@Service
public class PrizeServiceImpl implements PrizeService {

    @Autowired
    private PictureService pictureService;

    @Autowired
    private PrizeMapper prizeMapper;

    @Override
    public Long createPrize(CreatePrizeParam param, MultipartFile picFile) {
        // 1、上传图片
        String fileName = pictureService.savePicture(picFile);

        // 2、存库
        PrizeDO prizeDO = new PrizeDO();
        prizeDO.setName(param.getPrizeName());
        prizeDO.setDescription(param.getDescription());
        prizeDO.setImageUrl(fileName);
        prizeDO.setPrice(param.getPrice());
        prizeMapper.insert(prizeDO);
        return prizeDO.getId();
    }

    @Override
    public PageListDTO<PrizeDTO> findPrizeList(PageParam param) {
        // 1、设置总量
        int total = prizeMapper.count();

        // 2、查询当前页列表
        List<PrizeDTO> prizeDTOList = new ArrayList<>();
        List<PrizeDO> prizeDOList = prizeMapper.selectPrizeList(param.offset(),param.getPageSize());

        for (PrizeDO prizeDO:prizeDOList) {
            PrizeDTO dto = new PrizeDTO();
            dto.setPrizeId(prizeDO.getId());
            dto.setName(prizeDO.getName());
            dto.setDescription(prizeDO.getDescription());
            dto.setPrice(prizeDO.getPrice());
            dto.setImageUrl(prizeDO.getImageUrl());
            prizeDTOList.add(dto);
        }

        return new PageListDTO<>(total,prizeDTOList);
    }
}

